﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ProxyConfiguration.cs" company="3po.ru">
//   Author: Alexander Ulitin [support@3po.ru]
//   
//   This file is part of Conusic.
//   
//   Conusic is free software: you can redistribute it and/or modify
//   it under the terms of the GNU General Public License as published by
//   the Free Software Foundation, either version 3 of the License, or
//   (at your option) any later version.
//   
//   Conusic is distributed in the hope that it will be useful,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   GNU General Public License for more details.
//   
//   You should have received a copy of the GNU General Public License
//   along with Conusic.  If not, see http://www.gnu.org/licenses/.
// </copyright>
// <summary>
//   Description of ProxyConfiguration.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace ConusicUI
{
    using System;
    using System.Drawing;
    using System.Net;
    using System.Windows.Forms;

    using Conusic;
    using Conusic.Properties;

    /// <summary>
    /// Description of ProxyConfiguration.
    /// </summary>
    public partial class ProxyConfiguration : UserControl
    {
        #region Fields

        /// <summary>
        /// The connection successfully checked.
        /// </summary>
        private bool connectionSuccessfullyChecked = false;

        #endregion

        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="ProxyConfiguration"/> class.
        /// </summary>
        /// <exception cref="ArgumentOutOfRangeException">
        /// </exception>
        public ProxyConfiguration()
        {
            this.ConnectionSuccessfullyChecked = false;
            this.InitializeComponent();

            var proxyType = (Config.ProxyType)Settings.Default.ProxyType;
            switch (proxyType)
            {
                case Config.ProxyType.Automatic:
                    this.radioButtonAutoProxy.Select();
                    break;
                case Config.ProxyType.Direct:
                    this.radioButtonDirect.Select();
                    break;
                case Config.ProxyType.Manual:
                    this.radioButtonManual.Select();
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            this.SetEnablePasswordProxy(this.checkBoxAuthRequire.Checked);
            this.checkBoxAuthRequire.Checked = Settings.Default.ProxyAuth;
            this.textBoxAddress.Text = Settings.Default.ProxyAddress;
            this.textBoxPort.Text = Settings.Default.ProxyPort.ToString();
            this.textBoxUsername.Text = Settings.Default.ProxyUser;
            this.textBoxPassword.Text = Settings.Default.ProxyPass;
        }

        #endregion

        #region Public Properties

        /// <summary>
        /// Gets a value indicating whether connection successfully checked.
        /// </summary>
        public bool ConnectionSuccessfullyChecked
        {
            get
            {
                return this.connectionSuccessfullyChecked;
            }

            private set
            {
                this.connectionSuccessfullyChecked = value;
            }
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets the proxy type selected.
        /// </summary>
        /// <exception cref="ArgumentException">
        /// </exception>
        private Config.ProxyType proxyTypeSelected
        {
            get
            {
                if (this.radioButtonAutoProxy.Checked)
                {
                    return Config.ProxyType.Automatic;
                }
                else if (this.radioButtonDirect.Checked)
                {
                    return Config.ProxyType.Direct;
                }
                else if (this.radioButtonManual.Checked)
                {
                    return Config.ProxyType.Manual;
                }
                else
                {
                    throw new ArgumentException("no one radio button selected");
                }
            }
        }

        #endregion

        #region Public Methods and Operators

        /// <summary>
        /// The save settings.
        /// </summary>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        public bool SaveSettings()
        {
            if (!this.Validate())
            {
                return false;
            }

            this.SetProxySettings();

            Settings.Default.ProxyType = (int)this.proxyTypeSelected;
            Settings.Default.ProxyAuth = this.checkBoxAuthRequire.Checked;
            Settings.Default.ProxyUser = this.textBoxUsername.Text;
            Settings.Default.ProxyPass = this.textBoxPassword.Text;
            Settings.Default.ProxyAddress = this.textBoxAddress.Text;
            Settings.Default.ProxyPort = int.Parse(this.textBoxPort.Text);
            return true;
        }

        #endregion

        #region Methods

        /// <summary>
        /// The button 1 click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        /// <exception cref="WebException">
        /// </exception>
        private void Button1Click(object sender, EventArgs e)
        {
            if (!this.ValidateForm())
            {
                return;
            }

            this.SetProxySettings();

            this.UseWaitCursor = true;

            try
            {
                string page = SimpleHttp.RequestVkontaktePage("help.php?page=about");

                // Durov never remove himself :-)
                if (page.Contains(@"href=""/id1"""))
                {
                    this.textBoxResult.Text =
                        @"Все хорошо. Если в будущем будет появляться это окно, обратитесь к разработчику";
                    this.textBoxResult.BackColor = Color.LightGreen;
                    this.ConnectionSuccessfullyChecked = true;
                }
                else
                {
                    this.connectionSuccessfullyChecked = false;
                    throw new WebException(
                        "Страница получена, но ответ неверен. "
                        + "Возможно, закрыт доступ к Vkontakte.ru или используется неверный прокси сервер");
                }
            }
            catch (Exception exception)
            {
                this.textBoxResult.Text =
                    string.Format(
                        "Запрос неудачен. Произошла ошибка  {0}. "
                        + "Перепроверьте настройки прокси, в случае необходимости,"
                        + " обратитесь к вашему системному администратору {1}", 
                        exception.Message, 
                        DateTime.Now);
                this.textBoxResult.BackColor = Color.LightPink;
            }
            finally
            {
                this.UseWaitCursor = false;
            }
        }

        /// <summary>
        /// The check box auth require checked changed.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void CheckBoxAuthRequireCheckedChanged(object sender, EventArgs e)
        {
            this.SetEnablePasswordProxy(this.checkBoxAuthRequire.Checked);
        }

        /// <summary>
        /// The radio button checked changed.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void RadioButtonCheckedChanged(object sender, EventArgs e)
        {
            if (this.radioButtonAutoProxy.Checked)
            {
                this.SetEnableManualConfiguration(false);
            }
            else if (this.radioButtonDirect.Checked)
            {
                this.SetEnableManualConfiguration(false);
            }
            else if (this.radioButtonManual.Checked)
            {
                this.SetEnableManualConfiguration(true);
            }
        }

        /// <summary>
        /// The set enable manual configuration.
        /// </summary>
        /// <param name="withoutProxyAuthEnabled">
        /// The without proxy auth enabled.
        /// </param>
        private void SetEnableManualConfiguration(bool withoutProxyAuthEnabled)
        {
            this.textBoxAddress.Enabled = withoutProxyAuthEnabled;
            this.labelDelemiter.Enabled = withoutProxyAuthEnabled;
            this.labelAddress.Enabled = withoutProxyAuthEnabled;
            this.textBoxPort.Enabled = withoutProxyAuthEnabled;
            this.labelPort.Enabled = withoutProxyAuthEnabled;
        }

        /// <summary>
        /// The set enable password proxy.
        /// </summary>
        /// <param name="w">
        /// The w.
        /// </param>
        private void SetEnablePasswordProxy(bool w)
        {
            this.textBoxPassword.Enabled = w;
            this.textBoxUsername.Enabled = w;
            this.labelPassword.Enabled = w;
            this.labelLogin.Enabled = w;
        }

        /// <summary>
        /// The set proxy settings.
        /// </summary>
        private void SetProxySettings()
        {
            int port = int.Parse(this.textBoxPort.Text);
            Config.Instance.UpdateProxyParams(
                this.proxyTypeSelected, 
                this.checkBoxAuthRequire.Checked, 
                this.textBoxAddress.Text, 
                port, 
                this.textBoxUsername.Text, 
                this.textBoxPassword.Text);
        }

        /// <summary>
        /// The validate form.
        /// </summary>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        private bool ValidateForm()
        {
            this.errorProvider1.Clear();

            int x;
            bool validation = true;
            if (!int.TryParse(this.textBoxPort.Text, out x) || x > 65536 || x < 0)
            {
                this.errorProvider1.SetError(this.textBoxPort, @"Порт должен быть целым числом от 1 до 65536");
                validation = false;
            }

            if (this.radioButtonManual.Checked && string.IsNullOrEmpty(this.textBoxAddress.Text))
            {
                this.errorProvider1.SetError(this.textBoxAddress, @"Введите адрес прокси");
                validation = false;
            }

            if (this.checkBoxAuthRequire.Checked)
            {
                if (string.IsNullOrEmpty(this.textBoxUsername.Text))
                {
                    this.errorProvider1.SetError(this.textBoxUsername, @"введите пользователя прокси");
                    validation = false;
                }

                if (string.IsNullOrEmpty(this.textBoxPassword.Text))
                {
                    this.errorProvider1.SetError(this.textBoxPassword, @"введите пароль прокси");
                    validation = false;
                }
            }

            return validation;
        }

        #endregion
    }
}